﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WinApp.i18n;
using WinApp.Model;
using WinApp.Model.AjaxResult;
using WinApp.Until;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.ListView;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace WinApp.ViewModel
{
    public static class LoginIndexModel
    {
        public static AjaxResult token(LoginInfoInputDto dto)
        {
            AjaxResult ajaxResult = new AjaxResult();

            if (GlobalVariables.SystemSwitchModel == SwitchMode.OnLine)
            {
                ajaxResult = WebApiHelper.PostWebAPI<AjaxResult>("api/identity/token", dto, false);

                if (ajaxResult.Data != null)
                {
                    var strData = ajaxResult.Data.ToString();
                    if (!string.IsNullOrEmpty(strData))
                    {
                        var loginOutputData = JsonConvert.DeserializeObject<LoginInfoDataOutputDto>(strData);

                        WebApiHelper._Authorization = loginOutputData == null ? "" : loginOutputData.AccessToken;
                        WebApiHelper._RefreshToken = loginOutputData == null ? "" : loginOutputData.RefreshToken;
                        GlobalVariables.UserInfo = WebApiHelper.GetWebAPI<UserInfoOutputDto>("api/Admin/User/GetCurrentUserInfo");

                        var imageTemp = FileHelper.LoadImageFromWebUriAsync(GlobalVariables.UserInfo.HeadImg);
                        if (imageTemp != null)
                            GlobalVariables.UserInfo.HeadImage = imageTemp;

                        using (var db = new SqlLiteDbContext())
                        {
                            var currentUser = db.Users.Find(GlobalVariables.UserInfo.Id);
                            if (currentUser == null)
                            {//创建
                                db.Users.Add(new Model.EF_Model.User()
                                {
                                    BelongTorootId = GlobalVariables.UserInfo.BelongToRootId,
                                    Email = GlobalVariables.UserInfo.Email,
                                    EmployeeID = GlobalVariables.UserInfo.EmployeeID,
                                    FirstName = GlobalVariables.UserInfo.FirstName,
                                    HeadImg = GlobalVariables.UserInfo.HeadImg,
                                    LastName = GlobalVariables.UserInfo.LastName,
                                    NickName = GlobalVariables.UserInfo.NickName,
                                    PhoneNumber = GlobalVariables.UserInfo.PhoneNumber,
                                    Remark = GlobalVariables.UserInfo.Remark,
                                    TimeZoneId = GlobalVariables.UserInfo.TimeZoneId,
                                    UserName = GlobalVariables.UserInfo.UserName,
                                    PasswordHash = dto.password
                                });
                                db.SaveChanges();
                            }
                            else
                            {//更新
                                currentUser.BelongTorootId = GlobalVariables.UserInfo.BelongToRootId;
                                currentUser.Email = GlobalVariables.UserInfo.Email;
                                currentUser.EmployeeID = GlobalVariables.UserInfo.EmployeeID;
                                currentUser.FirstName = GlobalVariables.UserInfo.FirstName;
                                currentUser.HeadImg = GlobalVariables.UserInfo.HeadImg;
                                currentUser.LastName = GlobalVariables.UserInfo.LastName;
                                currentUser.NickName = GlobalVariables.UserInfo.NickName;
                                currentUser.PhoneNumber = GlobalVariables.UserInfo.PhoneNumber;
                                currentUser.Remark = GlobalVariables.UserInfo.Remark;
                                currentUser.TimeZoneId = GlobalVariables.UserInfo.TimeZoneId;
                                currentUser.UserName = GlobalVariables.UserInfo.UserName;
                                currentUser.PasswordHash = dto.password;
                                db.SaveChanges();
                            }
                        }
                    }
                }
            }
            else
            {
                using (var db = new SqlLiteDbContext())
                {
                    var findUser = db.Users.FirstOrDefault(x => x.UserName == dto.account);
                    if (findUser == null)
                    {
                        ajaxResult.Type = AjaxResultType.Info;
                        ajaxResult.Content = Language.GetLang("offLineNotFindUserInfo");
                    }
                    else if (findUser.PasswordHash != dto.password)
                    {
                        ajaxResult.Type = AjaxResultType.Info;
                        ajaxResult.Content = Language.GetLang("offLinePasswordError");
                    }
                    else
                    {
                        GlobalVariables.UserInfo = new UserInfoOutputDto
                        {
                            BelongToRootId = findUser.BelongTorootId,
                            Email = findUser.Email,
                            EmployeeID = findUser.EmployeeID,
                            FirstName = findUser.FirstName,
                            HeadImg = findUser.HeadImg,
                            LastName = findUser.LastName,
                            NickName = findUser.NickName,
                            PhoneNumber = findUser.PhoneNumber,
                            Remark = findUser.Remark,
                            TimeZoneId = findUser.TimeZoneId,
                            UserName = findUser.UserName,
                        };
                        var imageTemp = FileHelper.LoadImageFromWebUriAsync(GlobalVariables.UserInfo.HeadImg);
                        if (imageTemp != null)
                            GlobalVariables.UserInfo.HeadImage = imageTemp;

                        ajaxResult.Type = AjaxResultType.Success;
                    }
                }
            }

            return ajaxResult;
        }
    }
    public class LoginInputDto
    {
        public string UserName { get; set; }
        public string Password { get; set; }

    }
    public class LoginInfoInputDto
    {
        public string account { get; set; }
        public string password { get; set; }

        public string grantType { get; set; }

        public int tenantId { get; set; }

        public bool IsForceLogin { get; set; }

    }

    public class LoginInfoDataOutputDto
    {
        public string AccessToken { get; set; }
        public string RefreshToken { get; set; }
        public string RefreshUctExpires { get; set; }
    }

    public class UserInfoOutputDto
    {

        /// <summary>
        /// 获取或设置 用户编号
        /// </summary>
        public int Id { get; set; }

        /// <summary>
        /// 获取或设置 用户名
        /// </summary>
        public string UserName { get; set; }

        /// <summary>
        /// 获取或设置 员工号
        /// </summary>
        public string EmployeeID { get; set; }
        /// <summary>
        /// 获取或设置 FirstName
        /// </summary>
        public string FirstName { get; set; }
        /// <summary>
        /// 获取或设置 LastName
        /// </summary>
        public string LastName { get; set; }
        /// <summary>
        /// 获取或设置 个人简介
        /// </summary>
        public string Remark { get; set; }

        /// <summary>
        /// 获取或设置 用户昵称
        /// </summary>
        public string NickName { get; set; }

        /// <summary>
        /// 获取或设置 电子邮箱
        /// </summary>
        public string Email { get; set; }

        /// <summary>
        /// 获取或设置 表示用户是否已确认其电子邮件地址的标志
        /// </summary>
        public bool EmailConfirmed { get; set; }

        /// <summary>
        /// 获取或设置 手机号码
        /// </summary>
        public string PhoneNumber { get; set; }

        /// <summary>
        /// 获取或设置 手机号码是否已确认
        /// </summary>
        public bool PhoneNumberConfirmed { get; set; }

        /// <summary>
        /// 获取或设置 当任何用户锁定结束时，UTC的日期和时间。
        /// </summary>
        public DateTimeOffset? LockoutEnd { get; set; }

        /// <summary>
        /// 获取或设置 指示用户是否可以被锁定的标志。
        /// </summary>
        public bool LockoutEnabled { get; set; }

        /// <summary>
        /// 获取或设置 当前用户失败的登录尝试次数。
        /// </summary>
        public int AccessFailedCount { get; set; }

        /// <summary>
        /// 获取或设置 是否锁定当前信息
        /// </summary>
        public bool IsLocked { get; set; }

        /// <summary>
        /// 获取或设置 Created time
        /// </summary>
        public DateTime CreatedTime { get; set; }

        /// <summary>
        /// 获取或设置 角色信息集合
        /// </summary>
        public string[] Roles { get; set; }
        /// <summary>
        /// 用户时区
        /// </summary>
        public int? TimeZoneId { get; set; }
        /// <summary>
        /// Tenant ID
        /// </summary>
        public int? TenantId { get; set; }
        /// <summary>
        /// 飞行时长
        /// </summary>
        public int? FlightTime { get; set; }
        /// <summary>
        /// 所属公司
        /// </summary>
        public string CompanyName { get; set; }
        /// <summary>
        /// 职位/岗位
        /// </summary>
        public string JobPosition { get; set; }
        /// <summary>
        /// 毕业院校
        /// </summary>
        public string GraduateSchool { get; set; }
        /// <summary>
        /// Age
        /// </summary>
        public int? Age { get; set; }
        public DateTime? Birthday { get; set; }

        /// <summary>
        /// 出生地
        /// </summary>
        public string BirthPlace { get; set; }
        public int? BelongToRootId { get; set; }



        public string HeadImg { get; set; }

        public DateTime? EmploymentDate { get; set; }
        /// <summary>
        /// 过期日期
        /// </summary>
        public DateTime? ExpiredTime { get; set; }
        /// <summary>
        /// 获取或设置 IsTerminated
        /// </summary>
        public bool IsTerminated { get; set; }

        public int StudentStatus { get; set; }

        public string Basement { get; set; }
        public Image? HeadImage { get; set; } = FileHelper.loadImageFromLocalPath(@"FileFolder/Image/defaultTouxiang.png");

        /// 获取 扩展数据字典
        /// </summary>
        public IDictionary<string, string> ExtendData { get; } = new Dictionary<string, string>();
    }
}
